<template>
  <div class="about">
    {{ list }}
    <h1 @click="handleClick">{{ state.msg }} {{ inputValue }}</h1>
    账号：
    <input v-model="state.account" />
    密码：
    <input v-model="inputValue" />
    <button @click="handleLoginClick">登陆</button>
  </div>
</template>
<script lang="ts">
// setup为核心的书写语法，称为合成api (composition Api)
import { defineComponent, reactive, watchEffect, ref, watch } from 'vue'
import axios from 'axios'
// vue3使用路由方式
import { useRouter } from 'vue-router'
import { Toast } from 'vant'

export default defineComponent({
  // setup函数 没有this
  setup() {
    const router = useRouter()
    // reactive 定义响应式数据
    const state = reactive({
      msg: 'hello Vue!',
      account: '',
      password: '',
      list: [
        { id: 1, name: 'devin' },
        { id: 2, name: 'city' }
      ]
    })

    const inputValue = ref<number>(0)

    const list = ref([
      { id: 1, name: 'devin' },
      { id: 2, name: 'city' }
    ])

    setTimeout(() => {
      list.value.push({ id: 3, name: 'bei' })
    }, 3000)

    // 响应式追踪
    watchEffect(() => {
      console.log('监听数据:', list)
    }, {})

    watch(list.value, (v) => {
      console.log(v, 'v')
    })

    // 与vue2的watch基本一致 监听单一数据源，写法第一个参数是一个监听的对象，使用函数形式表示，第二个参数，是监听回调
    // watch(
    //   () => inputValue.value,
    //   (newVal, oldVal) => {
    //     console.log('newVal:', newVal)
    //     console.log('oldVal', oldVal)
    //   }
    // )

    // ref click
    const handleClick = function () {
      inputValue.value++
    }

    const handleLoginClick = async () => {
      const response = await axios.get('/api/login', {
        params: { account: state.account, password: inputValue.value }
      })
      const data = response.data
      if (data.code === 0) {
        window.localStorage.setItem('token', data.data.token)
        Toast.success('成功文案')
        router.push('/home')
      }
    }

    return {
      list,
      state,
      inputValue,
      handleLoginClick,
      handleClick
    }
  }
})
</script>
